package com.strongbj.iot.devices.hr.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.core.message.MessageHandleContext;
import com.strongbj.iot.devices.hr.message.HRMessage;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class HRResponseHandleContext extends SimpleChannelInboundHandler<HRMessage>  {
	private MessageHandleContext<HRMessage,Object> messageHandleContent;
	private static Logger logger = LogManager.getLogger(HRResponseHandleContext.class.getName());
	public static final ChannelGroup channels = new DefaultChannelGroup("HRChannelGroup",GlobalEventExecutor.INSTANCE);
	public static long count=0;
	public HRResponseHandleContext(String doorDirection, Integer labelCount){
		super();
		this.messageHandleContent = new MessageHandleContext<>();
		this.messageHandleContent.addHandleClass(new HRReadLabelInTriggerModeHandle(doorDirection, labelCount));  // 触发模式下处理标签信息的类
//		this.messageHandleContent.addHandleClass(new TestHRReadLabelInTriggerModeHandle());  // 触发模式下处理标签信息的类
		this.messageHandleContent.addHandleClass(new HRBootInfoHandle(doorDirection));  // 开机信息处理类
		this.messageHandleContent.addHandleClass(new HRHeartPackageHandle(doorDirection));  // 门禁心跳包处理类
		this.messageHandleContent.addHandleClass(new HRResetResponseHandle(doorDirection));  // 重启反馈处理类
		this.messageHandleContent.addHandleClass(new HRControlBuzzerSoundResponseHandle(doorDirection));  // 控制蜂鸣器发声处理类
	}
	
	@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("HR设备已连接"+ctx.channel().remoteAddress().toString());
        channels.add(ctx.channel());
		super.channelActive(ctx);
    }

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		logger.info("HR设备已断开"+ctx.channel().remoteAddress().toString());
		channels.remove(ctx.channel());
		this.messageHandleContent.clearHandleClass();
		super.channelInactive(ctx);
	}
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, HRMessage msg)
			throws Exception {
		if(msg==null) return;
		// 如果不是HR设备发送过来的，就不处理
		if(msg.getSequence()!=0x01) return;
		this.messageHandleContent.handle(ctx,msg);
	}
}
